package com.example.wifi_demo;

import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import androidx.annotation.NonNull;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class OkhtttpUtils {

    private final Handler mHandler; // 主线程Handler
    private final OkHttpClient mOkHttpClient; // OkHttpClient实例
    private static OkhtttpUtils sOkhtttpUtils;
    private String mToken;
    // JSON media type
    private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");

    private OkhtttpUtils() {
        mHandler = new Handler(Looper.getMainLooper());

        // 创建OkHttpClient实例
        mOkHttpClient = new OkHttpClient.Builder()
                .readTimeout(5000, TimeUnit.MILLISECONDS) // 设置读取超时时间
                .connectTimeout(5000, TimeUnit.MILLISECONDS) // 设置连接超时时间
                .writeTimeout(5000, TimeUnit.MILLISECONDS) // 设置写入超时时间
                .retryOnConnectionFailure(true) // 设置失败重试
                .build();
    }

    // 获取单例实例
    public static OkhtttpUtils getInstance() {
        if (sOkhtttpUtils == null) {
            synchronized (OkhtttpUtils.class) {
                if (sOkhtttpUtils == null) {
                    sOkhtttpUtils = new OkhtttpUtils();
                }
            }
        }
        return sOkhtttpUtils;
    }

    // 设置token
    public void setToken(String token) {
        mToken = token;
    }
    // 清除token
    public void clearToken() {
        mToken = null;
    }

    // 更新token
    public void updateToken(String newToken) {
        mToken = newToken;
    }
    // 自定义回调接口
    public interface OkCallback {
        void onFailure(Exception e); // 请求失败回调

        void onResponse(String json); // 请求成功回调
        void onImageResponse(Bitmap bitmap); // 请求图片成功回调
    }

    // 发起Get请求
    public void doGet(Context context, String url, Map<String, String> params, final OkCallback ycfOkCallback) {
        // 显示数据加载中
        showLoadingDialog(context);

        if (params != null && !params.isEmpty()) {
            StringBuilder urlBuilder = new StringBuilder(url);
            if (!url.contains("?")) {
                urlBuilder.append("?");
            } else {
                urlBuilder.append("&");
            }
            for (Map.Entry<String, String> entry : params.entrySet()) {
                urlBuilder.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
            }
            url = urlBuilder.toString();
        }

        Request.Builder requestBuilder = new Request.Builder()
                .get()
                .url(url);

        // 判断是否设置了token，如果设置了，则添加到请求头中
        if (mToken != null) {
            requestBuilder.addHeader("Authorization", mToken);
        }

        Request request = requestBuilder.build();

        Call call = mOkHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, final IOException e) {
                // 加载失败
                dismissLoadingDialog(context);
                if (ycfOkCallback != null) {
                    mHandler.post(() -> ycfOkCallback.onFailure(e));
                }
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                dismissLoadingDialog(context);
                if (response.isSuccessful()) {
                    final String json = Objects.requireNonNull(response.body()).string();
                    if (ycfOkCallback != null) {
                        mHandler.post(() -> ycfOkCallback.onResponse(json));
                    }
                } else {
                    // 加载失败
                    if (ycfOkCallback != null) {
                        mHandler.post(() -> ycfOkCallback.onFailure(new IOException("Response unsuccessful")));
                    }
                }
            }
        });
    }

    private ProgressDialog progressDialog;

    private void showLoadingDialog(Context context) {
        progressDialog = new ProgressDialog(context);
        progressDialog.setMessage("数据加载中...");
        progressDialog.setCancelable(false);
        progressDialog.show();
    }

    /**
     * 隐藏加载对话框（带参数Context）
     * @param context 上下文环境
     */
    private void dismissLoadingDialog(Context context) {
        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
    }

    /**
     * 隐藏加载对话框（无参数）
     */
    private void dismissLoadingDialog() {
        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
    }

    // 发起Post请求
    public void doPost( Context context,String url, Map<String, String> params, final OkCallback ycfOkCallback) {
        // 显示数据加载中
        showLoadingDialog(context);

        FormBody.Builder builder = new FormBody.Builder();
        if (params != null && !params.isEmpty()) {
            for (Map.Entry<String, String> entry : params.entrySet()) {
                builder.add(entry.getKey(), Objects.requireNonNull(entry.getValue()));
            }
        }
        FormBody formBody = builder.build();

        Request.Builder requestBuilder = new Request.Builder()
                .post(formBody)
                .url(url);

        // 判断是否设置了token，如果设置了，则添加到请求头中
        if (mToken != null) {
            requestBuilder.addHeader("Authorization", mToken);
        }

        Request request = requestBuilder.build();

        Call call = mOkHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, final IOException e) {
                dismissLoadingDialog(context);
                if (ycfOkCallback != null) {
                    mHandler.post(() -> ycfOkCallback.onFailure(e));
                }
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                dismissLoadingDialog(context);
                if (response.isSuccessful()) {
                    final String json = Objects.requireNonNull(response.body()).string();
                    if (ycfOkCallback != null) {
                        mHandler.post(() -> ycfOkCallback.onResponse(json));
                    }
                } else {
                    if (ycfOkCallback != null) {
                        mHandler.post(() -> ycfOkCallback.onFailure(new IOException("Response unsuccessful")));
                    }
                }
            }
        });
    }

    // 发起Post请求 with JSON body
    public void doPost(Context context, String url, String params, final OkCallback ycfOkCallback) throws JSONException {
        // 显示数据加载中
        showLoadingDialog(context);
        Log.e("psq","params == " + params);
        Log.e("psq","url == " + url);
        // Convert params map to JSON
        JSONObject jsonObject = new JSONObject(params);
        String jsonString = jsonObject.toString();
        RequestBody requestBody = RequestBody.create(JSON,jsonString);

        Request.Builder requestBuilder = new Request.Builder()
                .post(requestBody)
                .url(url);

        // 判断是否设置了token，如果设置了，则添加到请求头中
        if (mToken != null) {
            requestBuilder.addHeader("Authorization", mToken);
        }

        Request request = requestBuilder.build();

        Call call = mOkHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, final IOException e) {
                dismissLoadingDialog(context);
                if (ycfOkCallback != null) {
                    mHandler.post(() -> ycfOkCallback.onFailure(e));
                }
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                dismissLoadingDialog(context);
                if (response.isSuccessful()) {

                    MediaType contentType = response.body().contentType();
                    if (contentType != null && contentType.type().equals("image")) {
                        // Handle image response
                        InputStream inputStream = response.body().byteStream();
                        Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                        if (ycfOkCallback != null) {
                            mHandler.post(() -> ycfOkCallback.onImageResponse(bitmap));
                        }
                    } else {
                        final String json = Objects.requireNonNull(response.body()).string();
                        if (ycfOkCallback != null) {
                            mHandler.post(() -> ycfOkCallback.onResponse(json));
                        }
                    }

                } else {
                    if (ycfOkCallback != null) {
                        mHandler.post(() -> ycfOkCallback.onFailure(new IOException("Response unsuccessful")));
                    }
                }
            }
        });
    }
}
